#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:Summerday
import oss2
import os
import shutil

# 类定义
class OssClient:
    # 定义基本属性
    auth = None
    bucket = None
    service = None
    # 定义私有属性,私有属性在类外部无法直接进行访问
    __endpoint = None
    __bucket_name = None

    # 定义构造方法
    def __init__(self, access_key_id, access_key_secret, endpoint):
        self.__endpoint = endpoint
        self.auth = oss2.Auth(access_key_id, access_key_secret)
        self.service = oss2.Service(self.auth, endpoint)

    def __str__(self):
        return 'OSSClient (bucket = %s)' % self.__bucket_name

    # 设置bucket
    def set_bucket(self, bucket_name):
        self.__bucket_name = bucket_name
        self.bucket = oss2.Bucket(self.auth, self.__endpoint, bucket_name)

    # bucket是否存在
    @staticmethod
    def does_bucket_exist(bucket):
        try:
            bucket.get_bucket_info()
        except oss2.exceptions.NoSuchBucket:
            return False
        except:
            raise
        return True

    # 创建一个bucket，其中bucket
    def create_bucket(self, bucket_name):
        self.set_bucket(bucket_name)
        if OssClient.does_bucket_exist(self.bucket):
            print('bucket exist')
            return

        print('bucket not exist')
        self.bucket.create_bucket()
        print(self.__bucket_name + " created!")

    #  循环删除所有的prefix前缀的bucket
    def delete_buckets(self, prefix):
        def delete_single(buc):
            try:
                # 删除Bucket。
                buc.delete_bucket()
            except oss2.exceptions.BucketNotEmpty:
                objs = []
                for obj in oss2.ObjectIterator(buc):
                    print(obj.key)
                    objs.append(obj.key)
                result = buc.batch_delete_objects(objs)
                print(' '.join(result.deleted_keys))
                buc.delete_bucket()
            except oss2.exceptions.NoSuchBucket:
                print('bucket does not exist')

        for b in oss2.BucketIterator(self.service, prefix=prefix):
            buck = oss2.Bucket(self.auth, self.__endpoint, b.name)
            delete_single(buck)

    def upload_file(self, filename):
        '''
        上传功能：把本地位置的文件上传到目标位置 bucketName/filename
        :param filename: 本地位置
        '''
        if not os.path.isfile(filename):
            print(filename + " is not a file!")
            return
        self.bucket.put_object_from_file(filename, filename)
        print(filename + " upload_file!")

    def upload_directory(self, local):
        '''
        上传功能：把本地位置的文件上传到目标位置
        :param local: 本地位置
        '''
        if not os.path.isdir:
            print(local + " is not a directory!")
            return
        w = os.walk(local)
        for (dirpath, dirnames, filenames) in w:
            for file in filenames:
                self.bucket.put_object_from_file(file, os.path.join(local, file))
                print(file + " upload!")

    def download(self, prefix, download_path):
        '''
        批量下载至download_path，命名： download_path / bucketName / filename
        :param download_path：下载目录
        :param prefix: bucket前缀
        :return: 下载所有图片
        '''
        if os.path.exists(download_path):
            shutil.rmtree(download_path)

        os.mkdir(download_path)
        # 列举当前账号所有地域下的存储空间。
        for b in oss2.BucketIterator(self.service, prefix=prefix):
            buc = oss2.Bucket(self.auth, self.__endpoint, b.name)
            sub_dir = os.path.join(download_path, b.name)
            if os.path.exists(sub_dir):
                shutil.rmtree(sub_dir)

            os.mkdir(sub_dir)
            # 列举Bucket下的所有文件。
            for obj in oss2.ObjectIterator(buc):
                # 填写Object完整路径，完整路径中不包含Bucket名称，例如testfolder/exampleobject.txt。
                # 下载Object到本地文件，并保存到指定的本地路径D:\\localpath\\examplefile.txt。如果指定的本地文件存在会覆盖，不存在则新建。
                sub_file = os.path.join(sub_dir, obj.key)
                buc.get_object_to_file(obj.key, sub_file)
                print(sub_file + " downloaded successfully!")


if __name__ == '__main__':
    oss_client = OssClient('LTAI4GCpXVngaqbF6LMRMLhh', 'cmZyApbflzbyJRiVRqGfb28mrEUHfr', 'oss-cn-shanghai.aliyuncs.com')
    oss_client.create_bucket("packethyh1")
    oss_client.upload_directory("py")
    oss_client.download(prefix="packet", download_path="new_download")
    # new_download/packethyh1/test1.py
    new_download_path = os.path.join("new_download", "packethyh1", "test1.py")
    os.system("python " + new_download_path)
    oss_client.delete_buckets("packet")
